package org.neuedu.fly.util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.neuedu.fly.entity.vo.ResponseEntity;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUploadUtil {

    public static ResponseEntity fileUpload(HttpServletRequest request) {
        //创建工厂
        try {
            //通过循环遍历得到要处理的list对象
            String realPath = request.getServletContext().getRealPath("upload");
            File baseFile = new File(realPath);
            if (!baseFile.exists())baseFile.mkdirs();

            //通过工厂解析request
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

            List<FileItem> items = servletFileUpload.parseRequest(request);
            String fileName = null;
            for (FileItem item : items) {
                fileName = item.getName();
                long l = System.currentTimeMillis();
                int i  = new Double(Math.random()*10000).intValue();
                fileName = l+i+fileName;
                long fileSize = item.getSize();
                System.out.println(fileName+" "+fileSize);
                InputStream is = item.getInputStream();
                OutputStream os = new FileOutputStream(new File(baseFile,fileName));
                IOUtils.copy(is,os);
                os.close();
                is.close();
            }
            Map<String,String> map = new HashMap<>();
            //获取域名
            String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ request.getContextPath() + "/upload/" + fileName;
            map.put("src",basePath);
            map.put("fileName",fileName);
            System.out.println(GsonUtil.toJson(ResponseEntity.data(map)));
            return ResponseEntity.data(map);
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.error("上传失败");
    }
}
